import { commonReduxGenerator } from 'utils/reduxGenerator/index'
import axios from 'axios'

import { url, api } from 'config/api'

import { calcHouse } from 'config/money'

const switch_choice_house_type = 'switch_choice_house_type'

// 房源信息
// 就是选房那个界面所有的房源数据
export const {
  reducer,

  success,
  error,
  reset,
  loading,
  loaded,
  storeQuery
} = commonReduxGenerator({
  type: 'house',

  state: {
    // 选房方式
    // -1 默认值
    // 0  预选
    // 1  正式抢房
    type: -1,

    query: {},
    // 房源状态 1待售 2锁定 3认购 4签约 5销控
    data: []
  },

  action: [{
    action: switch_choice_house_type,
    result: (state, payload) => {
      return {
        ...state,
        type: payload
      }
    }
  }]
})

export function getHouse (params = {}, ignoreCache) {
  return async (dispatch, getState) => {
    const {
      house: {
        loading: _loading,
        msg,
        init,
        query,

        ...rest
      }
    } = getState()

    if (_loading) {
      return ['重复请求']
    }

    if (init && !ignoreCache) {
      return [null, { ...rest }]
    }

    dispatch(loading())

    const [err, res] = await axios.post(url.server + api.getHouse, {
      ...query,
      ...params
    })

    dispatch(loaded())

    if (err) {
      dispatch(error(err))

      return [err]
    }

    const {
      data,
      data: {
        builds
      }
    } = res

    dispatch(success({
      query: {
        ...query,
        ...params
      },
      data: (
        builds && builds.length ?
          builds.map(v => ({
            ...v,
            floors: v.floors.map(_v => ({
              ..._v,
              houses: _v.houses.map(__v => ({
                ...__v,
                ...calcHouse(__v)
              }))
            }))
          })) :
          []
      )
    }))

    // dispatch(storeQuery(params))

    return [null, data]
  }
}

export function switchChoiceHouseType (payload) {
  return {
    payload,
    type: switch_choice_house_type
  }
}
